<!-- 模板 -->
<template>
  <div class="login">
    <div class="img-wrap">
      <img src="../assets/logo.png" alt="" />
    </div>
    <!-- element-ui的form组件 -->
    <el-form
      :model="loginUser"
      ref="loginFormRef"
      :rules="loginFormRules"
      label-width=".8rem"
    >
      <el-form-item label="名称" prop="username">
        <el-input v-model="loginUser.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="loginUser.password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="login()">登录</el-button>
        <el-button @click="resetForm('loginFormRef')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { request } from '../utits/request.js'
export default {
  name: 'Login',
  data() {
    return {
      loginUser: {
        username: '',
        password: ''
      },
      //表单的验证规则
      loginFormRules: {
        username: [
          {
            required: true,
            message: '请输入用户名',
            trigger: ['blur', 'input', 'change']
          },
          {
            min: 2,
            max: 12,
            message: '用户名最小2位最大12位',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 12,
            message: '密码最小3位最大12位',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    //重置表单
    resetForm(formName) {
      let _this = this
      this.$nextTick(() => {
        _this.$refs[formName].resetFields()
      })
    },
    // 登录
    login() {
      //找到表单
      let form = this.$refs['loginFormRef']
      //表单的验证valid=false没通过验证，反之通过验证
      form.validate(async valid => {
        if (!valid) {
          return this.$message.error('请求正确填写用户信息')
        }
        //1、准备参数
        let option = {
          url: 'http://localhost:3000/users/login',
          method: 'post',
          data: this.loginUser
        }
        //2、发送请求
        let { data: res } = await request(option)
        //3、解析返回数据
        console.log(res)
        //4、执行下一步逻辑
      })
    }
  },
  created() {}
}
</script>

<style lang="less" scoped>
.login {
  width: 5rem;
  padding: 0.5rem;
  position: absolute;
  background: rgba(0, 0, 0, 0.3);
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  border-radius: 0.1rem;
  .img-wrap {
    text-align: center;
    margin-bottom: 0.2rem;
    img {
      border-radius: 50%;
    }
  }
}
</style>
